import NFT from './NftMarkerCreator.min.js';
export class ImageToNft {
    constructor() {
        this.$nft = new NFT()
        this.globalObj = {
            dpi: 0,
            nc: 0,
            w: 0,
            h: 0,
            arr: []
        }
    }
    /**
     * 图片转换nft
     * @param {String} url 图片地址
     * @param {Object} param 其他参数
     */
    async convert(url, param = {}) {
        try {
            let extJpg = url.substring(url.lastIndexOf('.'));
            await this.drawnCanvas(url)
            if (extJpg === '.png' || extJpg === '.PNG') {
                this.globalObj.dpi = param.dpi || 72;
            } else {
                throw new Error("请传入png图片类型")
            }
            return await this.generate()
        } catch (err) {
            return Promise.reject(new Error("ImageToNft:" + err.message))
        }

    }
    generate() {
        return new Promise(resolve => {
            let paramStr = [0, "tempFilename"].join(' ');
            setTimeout(() => {
                let StrBuffer = this.$nft._malloc(paramStr.length + 1);
                this.$nft.writeStringToMemory(paramStr, StrBuffer);

                let heapSpace = this.$nft._malloc(this.globalObj.arr.length * this.globalObj.arr.BYTES_PER_ELEMENT);
                this.$nft.HEAPU8.set(this.globalObj.arr, heapSpace);

                this.$nft._createImageSet(heapSpace, this.globalObj.dpi, this.globalObj.w, this.globalObj.h, this.globalObj.nc, StrBuffer);

                this.$nft._free(heapSpace);
                this.$nft._free(StrBuffer);

                resolve(this.createMarkerFiles())
            }, 500);
        })

    }
    createMarkerFiles() {
        let mime = "application/octet-stream";
        let filenameFset = "tempFilename.fset";
        let filenameIset = "tempFilename.iset";
        let filenameFset3 = "tempFilename.fset3";
        let contentIset = this.$nft.FS.readFile(filenameIset);
        let contentFset = this.$nft.FS.readFile(filenameFset);
        let contentFset3 = this.$nft.FS.readFile(filenameFset3);
        let hrefFset = window.URL.createObjectURL(new Blob([contentFset]), { type: mime });
        let hrefIset = window.URL.createObjectURL(new Blob([contentIset]), { type: mime });
        let hrefFset3 = window.URL.createObjectURL(new Blob([contentFset3]), { type: mime });
        return [hrefFset,hrefIset, hrefFset3]
    }
    drawnCanvas(url) {
        return new Promise((resolve, reject) => {
            let img = new Image();
            img.setAttribute("crossOrigin", "Anonymous");
            img.onload = () => {
                const canvasEl = document.createElement('canvas');
                canvasEl.setAttribute('width', img.width);
                canvasEl.setAttribute('height', img.height);
                const canvasCtx = canvasEl.getContext('2d');
                this.globalObj.w = img.width;
                this.globalObj.h = img.height;
                canvasCtx.drawImage(img, 0, 0, img.width, img.height);
                let imgData = canvasCtx.getImageData(0, 0, img.width, img.height);
                let newArr = [];
                let verifyColorSpace = this.detectColorSpace(imgData.data);
                if (verifyColorSpace == 1) {
                    for (let j = 0; j < imgData.data.length; j += 4) {
                        newArr.push(imgData.data[j]);
                    }
                } else if (verifyColorSpace == 3) {
                    for (let j = 0; j < imgData.data.length; j += 4) {
                        newArr.push(imgData.data[j]);
                        newArr.push(imgData.data[j + 1]);
                        newArr.push(imgData.data[j + 2]);
                    }
                }

                this.globalObj.nc = verifyColorSpace;
                let uint = new Uint8Array(newArr);
                this.globalObj.arr = uint;
                resolve(true)
            }
            img.onerror = (err) => {
                reject(err)
            }

            img.src = `${url}?t=${new Date().getTime()}`;
        })

    }
    detectColorSpace(arr) {
        let target = parseInt(arr.length / 4);
        let counter = 0;
        for (let j = 0; j < arr.length; j += 4) {
            let r = arr[j];
            let g = arr[j + 1];
            let b = arr[j + 2];
            if (r == g && r == b) {
                counter++;
            }
        }
        if (target == counter) {
            return 1;
        } else {
            return 3;
        }
    }
}